<?php
namespace plugin\ky_black\app\admin\controller;

use support\Request;
use support\Response;
use plugin\ky_black\app\admin\model\Product;
use plugin\ky_black\app\admin\model\ProductCategory;

class ProductController extends BaseController
{
    /**
     * 获取产品列表
     */
    public function list(Request $request): Response
    {
        $page = (int)$request->input('page', 1);
        $limit = (int)$request->input('limit', 15);
        
        $query = Product::with(['category', 'partner']);
        
        // 名称搜索
        if ($name = $request->input('params.name')) {
            $query->where('name', 'like', "%{$name}%");
        }
        
        // 分类筛选
        if ($categoryId = $request->input('params.category_id')) {
            $query->where('category_id', $categoryId);
        }
        
        // 商家筛选
        if ($partnerId = $request->input('params.partner_id')) {
            $query->where('partner_id', $partnerId);
        }
        
        // 状态筛选
        $status = $request->input('params.status');
        if ($status !== null && $status !== '') {
            $query->where('status', $status);
        }
        
        $total = $query->count();
        $list = $query->offset(($page - 1) * $limit)
                      ->limit($limit)
                      ->orderBy('sort', 'desc')
                      ->orderBy('product_id', 'desc')
                      ->get();
            
        return $this->success([
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ]);
    }

    /**
     * 添加产品
     */
    public function add(Request $request): Response
    {
        $data = $request->post();
        
        $product = new Product();
        $product->category_id = $data['category_id'];
        $product->partner_id = $data['partner_id'];
        $product->name = $data['name'];
        $product->description = $data['description'] ?? '';
        $product->price = $data['price'];
        $product->market_price = $data['market_price'];
        $product->images = $data['images'] ?? [];
        $product->status = $data['status'] ?? 1;
        $product->sort = $data['sort'] ?? 0;
        
        if ($product->save()) {
            return json_success('添加成功');
        }
        return json_error('添加失败');
    }

    /**
     * 编辑产品
     */
    public function edit(Request $request): Response
    {
        $data = $request->post();
        
        $product = Product::find($data['product_id']);
        if (!$product) {
            return json_error('产品不存在');
        }
        
        $product->category_id = $data['category_id'];
        $product->partner_id = $data['partner_id'];
        $product->name = $data['name'];
        $product->description = $data['description'] ?? $product->description;
        $product->price = $data['price'];
        $product->market_price = $data['market_price'];
        $product->images = $data['images'] ?? $product->images;
        $product->status = $data['status'] ?? $product->status;
        $product->sort = $data['sort'] ?? $product->sort;
        
        if ($product->save()) {
            return json_success('编辑成功');
        }
        return json_error('编辑失败');
    }

    /**
     * 删除产品
     */
    public function delete(Request $request): Response
    {
        $id = $request->input('product_id');
        
        if (Product::destroy($id)) {
            return json_success('删除成功');
        }
        return json_error('删除失败');
    }

    /**
     * 更新产品状态
     */
    public function updateStatus(Request $request): Response
    {
        $productId = $request->input('product_id');
        $status = (int)$request->input('status');

        if (!$productId) {
            return $this->error('参数错误');
        }

        try {
            $product = Product::findOrFail($productId);
            $product->status = $status;
            $product->save();
            return $this->success(null, '状态更新成功');
        } catch (\Exception $e) {
            return $this->error('状态更新失败：' . $e->getMessage());
        }
    }

    /**
     * 获取产品详情
     */
    public function detail(Request $request): Response
    {
        $productId = $request->input('id');
        if (!$productId) {
            return $this->error('参数错误');
        }

        $product = Product::with(['category'])->find($productId);
        if (!$product) {
            return $this->error('产品不存在');
        }

        return $this->success($product);
    }
}
